package org.freedoit.server;

import java.util.Date;
import java.util.logging.Logger;

import org.freedoit.client.RegisterService;
import org.freedoit.server.dao.DAOFactory;
import org.freedoit.server.dao.UserDAO;
import org.freedoit.server.om.User;
import org.freedoit.shared.exception.LogicException;
import org.freedoit.shared.exception.ServerException;
import org.freedoit.shared.util.Constants;
import org.freedoit.shared.util.Utils;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class RegisterServiceImpl extends RemoteServiceServlet implements RegisterService {

	private static final Logger log = Logger.getLogger(RegisterServiceImpl.class.getName());
	
	public String register(String username, String password) throws ServerException, LogicException {
		// TODO Auto-generated method stub
		String key = getKey(username, password);
		
		if (key == null) {
			log.severe("Failed to save password");
			throw new ServerException("Failed to save password");
		} else {
			UserDAO userDAO = DAOFactory.getUserDAO();
			
			User user = userDAO.findByUserName(username);
			if (user == null) {
				userDAO.persist(new User(username, key, new Date(), Constants.ACTIVE_INTEGER));
				return "Registered!!";
			} else {
				log.warning("User already existed");
				throw new LogicException("User already existed");
			}
		}
	}
	
	private String getKey(String username, String password) {
		return Utils.getMD5(password);
	}
}
